<template>
  <view class="detail-container">
    <!-- 应用信息卡片 -->
    <view class="app-card" v-if="appDetail && !showQuestions && !showResult">
      <view class="app-header">
        <view class="app-title">
          <image 
            class="app-icon" 
            :src="appDetail.appIcon || 'https://gitee.com/static/images/logo-black.svg'" 
            mode="aspectFill"
          />
          <view class="title-content">
            <text class="app-name">{{ appDetail.appName }}</text>
            <text class="app-type" :class="{ 'mbti': appDetail.appType === 1 }">
              {{ appDetail.appType === 1 ? '测评类测试' : '得分类测试' }}
            </text>
          </view>
        </view>
        <text class="app-desc">{{ appDetail.appDesc }}</text>
      </view>

      <view class="author-info">
        <image 
          class="author-avatar" 
          :src="appDetail.user?.userAvatar || 'https://gitee.com/static/images/logo-black.svg'" 
          mode="aspectFill"
        />
        <view class="author-detail">
          <text class="author-name">{{ appDetail.user?.userName || '未知用户' }}</text>
          <text class="create-time">创建于 {{ formatDate(appDetail.createTime) }}</text>
        </view>
      </view>

      <view class="app-stats">
        <view class="stat-item">
          <text class="stat-label">评分策略</text>
          <text class="stat-value">{{ appDetail.scoringStrategy === 1 ? '标准评分' : '自定义评分' }}</text>
        </view>
        <view class="stat-item">
          <text class="stat-label">审核状态</text>
          <text class="stat-value" :class="{ 'approved': appDetail.reviewStatus === 1 }">
            {{ appDetail.reviewStatus === 1 ? '已通过' : '未通过' }}
          </text>
        </view>
      </view>

      <!-- 开始测试按钮 -->
      <button class="start-test-btn" @click="startTest">开始测试</button>
    </view>

    <!-- 答题页面 -->
    <view class="questions-container" v-if="showQuestions && !showResult">
      <view class="question-header">
        <text class="question-progress">{{ currentIndex + 1 }}/{{ questions.length }}</text>
        <text class="question-title">{{ currentQuestion?.title }}</text>
      </view>

      <view class="options-list">
        <view 
          v-for="(option, index) in currentQuestion?.options" 
          :key="index"
          class="option-item"
          :class="{ 'selected': selectedAnswer === index }"
          @click="selectAnswer(index)"
        >
          <text class="option-key">{{ option.key }}</text>
          <text class="option-value">{{ option.value }}</text>
        </view>
      </view>

      <view class="action-buttons">
        <button 
          class="nav-btn prev" 
          :disabled="currentIndex === 0"
          @click="prevQuestion"
        >上一题</button>
        <button 
          class="nav-btn next" 
          :disabled="currentIndex === questions.length - 1"
          @click="nextQuestion"
        >下一题</button>
      </view>

      <button 
        class="submit-btn" 
        :class="{ 'loading': isSubmitting }"
        :disabled="isSubmitting"
        @click="submitTest"
      >
        <text v-if="!isSubmitting">提交答案</text>
        <view v-else class="loading-container">
          <view class="loading-spinner"></view>
          <text>提交中...</text>
        </view>
      </button>
    </view>

    <!-- 结果页面 -->
    <view class="result-container" v-if="showResult">
      <view class="result-header">
        <image 
          class="user-avatar" 
          :src="testResult.user?.userAvatar" 
          mode="aspectFill"
        />
        <text class="user-name">{{ testResult.user?.userName }}</text>
      </view>
      
      <view class="result-title">
        <text class="title-text">{{ testResult.resultName }}</text>
      </view>
      
      <view class="result-desc">
        <text class="desc-text">{{ testResult.resultDesc }}</text>
      </view>
      
      <view class="result-choices">
        <text class="choices-title">答题详情：</text>
        <view 
          v-for="(choice, index) in testResult.choices" 
          :key="index"
          class="choice-item"
        >
          <text class="question-num">第{{ index + 1 }}题：</text>
          <text class="choice-value">选择了 {{ choice }}</text>
        </view>
      </view>
      
      <button class="back-btn" type="primary" @click="goBack">返回列表</button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getAppVoById } from '@/utils/api.js'
import request from '@/utils/request.js'

const appDetail = ref(null)
const showQuestions = ref(false)
const questions = ref([])
const currentIndex = ref(0)
const selectedAnswer = ref(null)
const userAnswers = ref([])
const uniqueId = ref(null)
const showResult = ref(false)
const testResult = ref(null)
const isSubmitting = ref(false)

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 获取应用详情
const getAppDetail = async (id) => {
  try {
    const res = await getAppVoById(id)
    
    if (res.code === 0 && res.data) {
      appDetail.value = res.data
    } else {
      uni.showToast({
        title: '获取详情失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('获取应用详情失败:', error)
    uni.showToast({
      title: '获取详情失败',
      icon: 'none'
    })
  }
}

// 获取题目列表
const getQuestions = async (appId) => {
  try {
    const res = await request({
      url: '/api/question/list/page/vo',
      method: 'POST',
      data: {
        appId,
        current: 1,
        pageSize: 20,
        sortField: 'createTime',
        sortOrder: 'descend'
      }
    })

    if (res.code === 0 && res.data?.records) {
      questions.value = res.data.records
      // 获取第一个问题的所有题目
      const firstQuestion = questions.value[0]
      if (firstQuestion && firstQuestion.questionContent) {
        questions.value = firstQuestion.questionContent
        // 初始化答案数组
        userAnswers.value = new Array(questions.value.length).fill(null)
        showQuestions.value = true
      }
    }
  } catch (error) {
    console.error('获取题目失败:', error)
    uni.showToast({
      title: '获取题目失败',
      icon: 'none'
    })
  }
}

// 获取当前题目
const currentQuestion = computed(() => {
  if (!questions.value.length) return null
  return questions.value[currentIndex.value]
})

// 选择答案
const selectAnswer = (index) => {
  selectedAnswer.value = index
  // 将数字索引转换为字母选项
  userAnswers.value[currentIndex.value] = currentQuestion.value.options[index].key
}

// 上一题
const prevQuestion = () => {
  if (currentIndex.value > 0) {
    currentIndex.value--
    selectedAnswer.value = userAnswers.value[currentIndex.value]
  }
}

// 下一题
const nextQuestion = () => {
  if (currentIndex.value < questions.value.length - 1) {
    currentIndex.value++
    selectedAnswer.value = userAnswers.value[currentIndex.value]
  }
}

// 获取唯一ID
const generateUniqueId = async () => {
  try {
    const res = await request({
      url: '/api/userAnswer/generate/id',
      method: 'GET'
    })
    
    if (res.code === 0 && res.data) {
      uniqueId.value = res.data
    } else {
      console.error('获取唯一ID失败')
    }
  } catch (error) {
    console.error('获取唯一ID失败:', error)
  }
}

// 获取答题结果
const getAnswerResult = async (id) => {
  try {
    const res = await request({
      url: '/api/userAnswer/get/vo?id=' + id,
      method: 'GET',
    })
    
    if (res.code === 0 && res.data) {
      testResult.value = res.data
      showQuestions.value = false
      showResult.value = true
    } else {
      uni.showToast({
        title: '获取结果失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('获取答题结果失败:', error)
    uni.showToast({
      title: '获取结果失败',
      icon: 'none'
    })
  }
}

// 返回列表
const goBack = () => {
  uni.navigateBack()
}

// 提交测试
const submitTest = async () => {
  if (isSubmitting.value) return
  
  if (!uniqueId.value) {
    uni.showToast({
      title: '系统错误，请重试',
      icon: 'none'
    })
    return
  }

  if (userAnswers.value.includes(null)) {
    uni.showToast({
      title: '请完成所有题目',
      icon: 'none'
    })
    return
  }

  try {
    isSubmitting.value = true
    const res = await request({
      url: '/api/userAnswer/add',
      method: 'POST',
      data: {
        appId: appDetail.value.id,
        choices: userAnswers.value,
        id: uniqueId.value
      }
    })

    if (res.code === 0) {
      uni.showToast({
        title: '提交成功',
        icon: 'success'
      })
      // 获取答题结果
      setTimeout(async () => {
        await getAnswerResult(uniqueId.value)
      }, 1000)
    } else {
      uni.showToast({
        title: res.message || '提交失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('提交答案失败:', error)
    uni.showToast({
      title: '提交失败',
      icon: 'none'
    })
  } finally {
    isSubmitting.value = false
  }
}

// 开始测试
const startTest = () => {
  if (!appDetail.value?.id) return
  getQuestions(appDetail.value.id)
}

// 页面加载时获取数据
onLoad(async ({ id }) => {
  if (id) {
    await generateUniqueId()
    await getAppDetail(id)
  } else {
    uni.showToast({
      title: '无效的应用ID',
      icon: 'none'
    })
  }
})
</script>

<style scoped>
.detail-container {
  padding: 30rpx;
  background: #f5f6fa;
  min-height: 100vh;
}

.app-card {
  background: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.05);
}

.app-header {
  margin-bottom: 30rpx;
}

.app-title {
  display: flex;
  align-items: center;
  gap: 20rpx;
  margin-bottom: 16rpx;
}

.app-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 16rpx;
  background: #f5f5f5;
}

.title-content {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.app-name {
  font-size: 40rpx;
  font-weight: bold;
  color: #333;
}

.app-type {
  font-size: 24rpx;
  padding: 4rpx 16rpx;
  border-radius: 12rpx;
  background: #E8F5E9;
  color: #4CAF50;
}

.app-type.mbti {
  background: #E3F2FD;
  color: #2196F3;
}

.app-desc {
  font-size: 28rpx;
  color: #666;
  line-height: 1.5;
}

.author-info {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 2rpx solid #f5f5f5;
}

.author-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 40rpx;
  margin-right: 20rpx;
}

.author-detail {
  display: flex;
  flex-direction: column;
}

.author-name {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.create-time {
  font-size: 24rpx;
  color: #999;
  margin-top: 4rpx;
}

.app-stats {
  display: flex;
  justify-content: space-between;
  padding: 30rpx 0;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-label {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 8rpx;
}

.stat-value {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.stat-value.approved {
  color: #4CAF50;
}

.start-test-btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  background: #2196F3;
  color: #fff;
  border-radius: 44rpx;
  font-size: 32rpx;
  margin-top: 40rpx;
  border: none;
}

.start-test-btn:active {
  opacity: 0.9;
}

.questions-container {
  background: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  min-height: 100vh;
}

.question-header {
  margin-bottom: 40rpx;
}

.question-progress {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 20rpx;
  display: block;
}

.question-title {
  font-size: 36rpx;
  color: #333;
  font-weight: 500;
  line-height: 1.5;
  display: block;
}

.options-list {
  margin: 40rpx 0;
}

.option-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  transition: all 0.3s ease;
}

.option-item.selected {
  border-color: #2196F3;
  background: #E3F2FD;
}

.option-key {
  width: 60rpx;
  height: 60rpx;
  background: #f5f5f5;
  border-radius: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: #666;
  margin-right: 20rpx;
}

.option-value {
  font-size: 32rpx;
  color: #333;
  flex: 1;
}

.action-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 40rpx;
}

.nav-btn {
  width: 200rpx;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  border-radius: 40rpx;
  font-size: 28rpx;
  background: #f5f5f5;
  color: #666;
  border: none;
}

.nav-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.submit-btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  background: #2196F3;
  color: #fff;
  border-radius: 44rpx;
  font-size: 32rpx;
  margin-top: 60rpx;
  border: none;
  position: relative;
  overflow: hidden;
}

.submit-btn.loading {
  background: #90CAF9;
  pointer-events: none;
}

.loading-container {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10rpx;
}

.loading-spinner {
  width: 36rpx;
  height: 36rpx;
  border: 4rpx solid #fff;
  border-top-color: transparent;
  border-radius: 50%;
  display: inline-block;
  animation: spin 0.8s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.result-container {
  padding: 40rpx;
  background: #fff;
  border-radius: 20rpx;
  margin: 20rpx;
}

.result-header {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.user-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 40rpx;
  margin-right: 20rpx;
}

.user-name {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
}

.result-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #2196F3;
  margin-bottom: 20rpx;
  text-align: center;
}

.result-desc {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
  margin-bottom: 30rpx;
  padding: 20rpx;
  background: #f5f5f5;
  border-radius: 12rpx;
}

.result-choices {
  margin-top: 30rpx;
}

.choices-title {
  font-size: 30rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 20rpx;
}

.choice-item {
  display: flex;
  align-items: center;
  padding: 10rpx 0;
}

.question-num {
  font-size: 28rpx;
  color: #666;
  width: 120rpx;
}

.choice-value {
  font-size: 28rpx;
  color: #333;
}

.back-btn {
  margin-top: 40rpx;
  width: 100%;
}
</style> 